package com.psmz.mqim.job;

import java.io.IOException;
import java.util.Observable;
import java.util.logging.Logger;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.ibm.mq.MQException;
import com.psmz.mqim.model.IMMessage;
import com.psmz.mqim.service.InstantMessaging;
import com.psmz.mqim.service.NoMessageException;

/**
 * Sprawdza wiadomosci w kolejce
 * 
 * @author pszwarc
 * 
 */
public class MessagePoller extends Observable implements Runnable {

	private InstantMessaging imService;
	private static final long CHECK_INTERVAL = 150; // 150 ms

	public MessagePoller(InstantMessaging imService) {
		this.imService = imService;
	}

	@Override
	public void run() {
		while (true) {
			IMMessage message = null;
			try {
				message = imService.receive();
				if (message != null) {
					setChanged();
					notifyObservers(message);
				}
			} catch (NoMessageException e) {
				try {
					Thread.sleep(CHECK_INTERVAL);
				} catch (InterruptedException e1) {
					System.err.println(e1.toString());
				}
			} catch (MQException e) {
				System.err.println(e.toString());
			} catch (IOException e) {
				System.err.println(e.toString());
			} catch (ParserConfigurationException e) {
				System.err.println(e.toString());
			} catch (SAXException e) {
				System.err.println(e.toString());
			}

		}
	}

}
